package com.after.saas.common.utils;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.codec.Hex;

import java.security.MessageDigest;

/**
 * @Classname PasswordUtil
 * @Description TODO
 * @Date 2021/7/15 3:36
 * @Auther after
 */
public class PasswordUtil {

    /**
     * 生成含有随机盐的密码
     */
    public static HashPassword generate(String plainText) {
        String salt = HashUtil.generateSalt(32);
        String password = HashUtil.md5(plainText, salt);
        return new HashPassword(password, salt);
    }

    /**
     * 校验密码是否正确
     */
    public static boolean verify(String plainText, HashPassword hashPassword) {
        String curPasswd = HashUtil.md5(plainText, hashPassword.salt);
        return StringUtils.equals(curPasswd, hashPassword.password);
    }

    /**
     * 获取十六进制字符串形式的MD5摘要
     */
    public static String md5Hex(String src) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] bs = md5.digest(src.getBytes());
            return new String(Hex.encode(bs));
        } catch (Exception e) {
            return null;
        }
    }

    public static class HashPassword {
        public String password;
        public String salt;

        public HashPassword(String password, String salt) {
            this.password = password;
            this.salt = salt;
        }
    }

    public static void main(String[] args) {
        String str = "123456";
        HashPassword hashPassword = generate(str);
        HashPassword oldPasswd = new HashPassword("cfb28835051800ebb8eca8a8a5d5805a", "lyEu4cG4fbLIKzSqKdt-Y5lSJVZ01sEq");
        System.out.println(JSON.toJSONString(hashPassword));
        System.out.println("flag=" + verify(str,hashPassword));
        System.out.println(verify(str, oldPasswd));
    }
}
